/*
 *   Copyright (C) 2009  Jens Kieselbach
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 * 
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 * 
 *   You may obtain a copy of the License at http://www.gnu.org/licenses/gpl.html
 */

package de.kieselbach.grootional.util

import de.kieselbach.grootional.value.*
import java.sql.*
import java.util.logging.*

class DatabaseConnectionPool {

    String description
    ConnectionValue connectionValue

    int size = 2
    def pool = [] as List

    DatabaseConnectionPool(String d, ConnectionValue v, int s = 2) {

        description = d
        connectionValue = v
        size = 2
    }

    def synchronized getConnection() {

        if(pool.size() > 0) {
            return pool.remove(0)
        }
        else {
            return new DatabaseConnection(DatabaseUtils.getConnection(connectionValue), this)
        }
    }

    synchronized closeConnection(DatabaseConnection con) {

        try {
            con.connection.rollback()
        }
        catch(Exception exc) {
            Logger.getLogger(getClass().name).log(Level.SEVERE, 'Unable to rollback connection!', exc)
        }

        if(pool.size() < size) {
            pool.add(con)
        }
        else {
            con.connection.close()
        }
    }

    synchronized dispose() {

        pool.each() {con ->
            con.connection.close()
        }
        pool.clear()
    }
}
